package com.heima.article.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleConfigService;
import com.heima.article.service.ApArticleContentService;
import com.heima.article.service.ApArticleHtmlService;
import com.heima.article.service.ApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigService apArticleConfigService;


    @Autowired
    private ApArticleContentService apArticleContentService;


    @Autowired
    private ApArticleHtmlService apArticleHtmlService;

    /**
     * 加载文章 更多 更新 type（区分更多还是更新）
     */
    @Override
    public ResponseResult loadArticle(int type, ArticleHomeDto dto) {
        List<ApArticle> apArticles = apArticleMapper.loadArticle(type, dto);
        return ResponseResult.okResult(apArticles);
    }

    /**
     * 文章的创建和更新 App文章相关数据
     */
    @Override
    @GlobalTransactional
    public ResponseResult saveOrUpdateArticle(ArticleDto dto) {
        log.info("文章的创建和更新 App文章相关数据开始 dto ======>>>>{}",dto);

        //1. 判断参数是否为空
        if (StringUtils.isBlank(dto.getTitle()) || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2. 将dto复制给pojo
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);

        //3. id参数无值就创建文章相关数据
        if (apArticle.getId() == null) {

            //3.1 保存ap_article表数据
            // TODO 保存文章信息时,图片信息没保存(暂定原因:image字段 一个 是 封面 一个是 文章)
            this.save(apArticle);

            //3.2 保存ap_article_config表数据
            ApArticleConfig apArticleConfig = new ApArticleConfig();
            apArticleConfig.setArticleId(apArticle.getId()); //app文章主表id
            apArticleConfig.setIsComment(true); // true -1 允许评论
            apArticleConfig.setIsForward(true); // true -1 允许转发
            apArticleConfig.setIsDelete(false); // false - 0 未删除
            apArticleConfig.setIsDown(false); // false - 0 未下架
            apArticleConfigService.save(apArticleConfig);

            //3.3 保存ap_article_content表数据
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId()); //app文章主表id
            apArticleContent.setContent(dto.getContent()); //文章内容
            apArticleContentService.save(apArticleContent);

        } else {
            //4. id参数有值就更新文章相关数据
            //4.1 判断文章是否存在
            int countApArticle = this.count(Wrappers.<ApArticle>lambdaQuery().eq(ApArticle::getId, apArticle.getId()));
            if (countApArticle <= 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"APP文章不存在");
            }

            //4.2 更新文章
            this.updateById(apArticle);

            //4.3 判断内容是否存在
            int countApArticleContent = apArticleContentService.count(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, apArticle.getId()));
            if (countApArticleContent <= 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"APP文章内容不存在");
            }

            //4.4 更新文章内容
            apArticleContentService.update(Wrappers.<ApArticleContent>lambdaUpdate()
                    .eq(ApArticleContent::getArticleId, apArticle.getId()) // 更新条件
                    .set(ApArticleContent::getContent, dto.getContent()) // 更新内容
            );
        }

        //5. 异步调用生成文章详情页(提交到线程池中执行)
        apArticleHtmlService.generatorHtml(apArticle, dto.getContent());
        //5. 响应文章ID
        return ResponseResult.okResult(apArticle.getId());
    }
}
